package com.easy.service.impl;

import com.easy.bean.Admin;
import com.easy.mapper.AdminDao;
import com.easy.service.AdminService;
import com.easy.util.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional(rollbackFor = Exception.class)
public class AdminServiceImpl implements AdminService {

    private static final String CACHE_NAME = "admin";

    @Autowired
    AdminDao adminDao;

    @Override
    @CacheEvict(value = CACHE_NAME, key = "'admin:' + #p0.id", condition = "#result != null")
    public Admin add(Admin admin) {
        // 新增数据
        adminDao.add(admin);
        // 通过主键查询数据库的数据
        Admin result = adminDao.one(admin.getId());
        return result;
    }

    @Override
    @CacheEvict(value = CACHE_NAME, key = "'admin:id:' + #p0")
    public int del(Integer id) {
        return adminDao.del(id);
    }

    @Override
    @CacheEvict(value = CACHE_NAME, key = "'admin:' + #p0.id", condition = "#p0 != null and #p0.id != null")
    public Admin edit(Admin admin) {
        adminDao.edit(admin);
        Admin result = adminDao.one(admin.getId());
        return result;
    }

    @Override
    @Cacheable(value = CACHE_NAME, key = "'admin:list:' + T(java.util.Objects).hash(#p0)", unless = "#result == null or #result.isEmpty()")
    public List<Admin> all(Admin admin) {
        return adminDao.all(admin);
    }

    @Override
    @Cacheable(value = CACHE_NAME, key = "'admin:id:' + #p0", unless = "#result == null")
    public Admin one(Integer id) {
        return adminDao.one(id);
    }

    @Override
    public void page(Page page, Admin admin) {
        int count = adminDao.pageCount(admin);
        Object data = adminDao.page(page, admin);
        page.setCount(count);
        page.setData(data);
    }
}
